<template>
  <div>
    <el-select clearable placeholder="请选择省份" v-model="province">
      <el-option v-for="item in areas" :key="item.code" :value="item.code" :label="item.name"></el-option>
    </el-select>
    <el-select clearable :disabled="!province" style="margin: 0 10px" placeholder="请选择城市" v-model="city">
      <el-option v-for="item in selectCity" :key="item.code" :value="item.code" :label="item.name"></el-option>
    </el-select>
    <el-select clearable :disabled="!province || !city" placeholder="请选择区域" v-model="area">
      <el-option v-for="item in selectArea" :key="item.code" :value="item.code" :label="item.name"></el-option>
    </el-select>
  </div>
</template>

<script lang="ts" setup>
import {ref, watch} from "vue";
import cityData from '../../../lib/pca-code.json'

export interface AreaItem {
  name: string,
  code: string,
  children?: AreaItem[]
}

export interface Data {
  name: string,
  code: string
}

let province = ref<string>('')
let city = ref<string>('')
let area = ref<string>('')
let areas = ref(cityData)

let selectCity = ref<AreaItem[]>([])
watch(() => province.value, value => {
  if(value) {
    let data = areas.value.find(item => item.code === province.value)!.children
    selectCity.value = data
  }
  city.value = ''
  area.value = ''
})

let selectArea = ref<AreaItem[]>([])
watch(() => city.value, value => {
  if(value) {
    let data = selectCity.value.find(item => item.code === city.value)!.children!
    selectArea.value = data
  }
  area.value = ''
})

let emits = defineEmits(['change'])
watch(() => area.value, value => {
  if(value) {
    let provinceData: Data = {
      name: areas.value.find(item => item.code === province.value)!.name,
      code: province.value
    }
    let cityData: Data = {
      name: selectCity.value.find(item => item.code === city.value)!.name,
      code: city.value
    }
    let areaData: Data = {
      name: selectArea.value.find(item => item.code === value)!.name,
      code: value
    }
    // console.log(provinceData, cityData, areaData)
    emits('change', {
      province: provinceData,
      city: cityData,
      area: areaData
    })
  }

})


</script>

<style scoped>

</style>